package com.wiwf.model.security.filter;

import com.wiwf.model.bean.SysUserVoto;
import com.wiwf.model.security.service.SysTokenService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Token验证过滤器
 * 在每次请求时验证Redis中token的有效性
 * @author kehui
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private SysTokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        String token = tokenService.getToken(request);
        
        // 如果存在token，验证其有效性
        if (!ObjectUtils.isEmpty(token)) {
            SysUserVoto tokenUser = tokenService.getTokenUser(response, request);
            
            // 如果token无效或用户信息为空
            if (ObjectUtils.isEmpty(tokenUser) || ObjectUtils.isEmpty(tokenUser.getName())) {
            	clearContext(response, request);
            }
        } else {
        	clearContext(response, request);
        }
        
        filterChain.doFilter(request, response);
    }
    
    private void clearContext(HttpServletResponse response, HttpServletRequest request) {
        // 清除token
        tokenService.delTokenUser(request);
        tokenService.delToken(response);
    	// 清除安全上下文
        SecurityContextHolder.clearContext();
	}
}